<template>
  <div>
    <el-card style="margin:20px">
      <menus @getcatagory="getcatagoryList" :show="!ishowTable"></menus>
    </el-card>
    <el-card>
      <div v-show="ishowTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性</el-button>
        <el-table border :data="list">
          <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
          <el-table-column label="属性名称" width="180" prop="attrName">

          </el-table-column>
          <el-table-column label="属性列表值" prop="tmName">
            <!-- //作用域插槽 -->
            <template slot-scope="{ row, $index }">
              <el-tag type="warning" v-for="item in row.attrValueList" :key="item.id" style="margin:0 20px">{{
                item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="{row,$index}">
              <el-button size="mini" type="info" icon="el-icon-edit" @click="updateAttr(row)">修改</el-button>
              <el-button size="mini" type="warning" icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div v-show="!ishowTable">
        <!-- form -->
        <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" style="width:500px" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" icon="el-icon-plus" @click="addAttrList"
          :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-button @click="ishowTable = true">取消</el-button>
        <!-- table -->
        <el-table style="width: 100%;margin:20px 0;" border :data="attrInfo.attrValueList">
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <!-- 聚焦 -->
          <el-table-column label="属性值名称">
            <template slot-scope="{row,$index}">
              <el-input v-model="row.valueName" :ref="$index" size="mini" v-if="row.flag"
                @blur="toLook(row)"></el-input>
              <span v-else @click="toEdit(row, $index)" style="display: block;">{{ row.valueName }}</span>
            </template>
            <!-- pop -->
          </el-table-column>
          <el-table-column width="180" label="操作">
            <template slot-scope="{row,$index}">
              <el-popconfirm :title="`确定删除${row.valueName}?`" @onConfirm="deleteAttrValue($index)"">
                <el-button type=" danger" size="mini" icon="el-icon-delete" slot="reference"></el-button>
              </el-popconfirm>
            </template>


          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr">保存</el-button>
        <el-button @click="ishowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// import cloneDeep from "lodash/cloneDeep";
export default {

  name: 'attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      list: [],
      ishowTable: true,
      //收集添加属性的属性信息
      attrInfo: {
        attrName: "", // 属性名
        attrValueList: [
          //属性名中属性值，因为属性值可以是多个，因此需要的是数组
          // {
          // attrId: 0, //属性的id
          // valueName: "", //属性值
          // },
        ],
        categoryId: 0, //category3Id
        categoryLevel: 3,
      },

    }
  },
  methods: {
    getcatagoryList({ categoryId, level }) { //解构

      if (level == 1) {
        this.category1Id = categoryId;
        // this.category2Id = '';
        // this.category3Id = '';
      } else if (level == 2) {
        this.category2Id = categoryId;
        this.category3Id = '';
      } else {
        //代表三级分类的id有了
        this.category3Id = categoryId;

        //发请求获取平台的属性数据
        // console.log(this.category1Id, this.category2Id, this.category3Id);

        this.getAttrList();

      }
    },
    //获取平台属性的数据
    //当用户确定三级分类的数据时候，可以向服务器发请求获取平台属性进行展示
    async getAttrList() {
      //获取分类的ID
      const { category1Id, category2Id, category3Id } = this;
      //获取属性列表的数据
      let result = await this.$API.attr.reqAttrList(
        category1Id,
        category2Id,
        category3Id
      );

      if (result.code == 200) {
        this.list = result.data;
      }
    },
    addAttrList() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, //属性的id
        valueName: '', //属性值
        flag: true
      })
      this.$nextTick(() => {
        let len = this.attrInfo.attrValueList.length - 1
        this.$refs[len].focus()
      })
    },
    addAttr() {
      this.ishowTable = false,
        this.attrInfo = {
          attrName: "", // 属性名
          attrValueList: [
            //属性名中属性值，因为属性值可以是多个，因此需要的是数组
            // {
            // attrId: 0, //属性的id
            // valueName: "", //属性值
            // },
          ],
          categoryId: this.category3Id, //category3Id
          categoryLevel: 3,
        }


    },
    toLook(row) {

      if (row.valueName.trim() == '') {
        this.$message('请你输入一个正常的属性值');
        return;
      }
      let res = this.attrInfo.attrValueList.some((item) => {
        if (row != item) {
          return row.valueName == item.valueName
        }
      })
      if (res) {
        return
      }
      row.flag = false
    },
    updateAttr(row, index) {
      this.ishowTable = false
      // this.attrInfo = cloneDeep(row);
      this.attrInfo = JSON.parse(JSON.stringify(row))
      //在修改某一个属性的时候，将相应的属性值元素添加上flag这个标记
      this.attrInfo.attrValueList.forEach((item) => {
        //这样书写也可以给属性值添加flag自动，但是会发现视图不会跟着变化（因为flag不是响应式数据）
        //因为Vue无法探测普通的新增 property,这样书写的属性并非响应式属性（数据变化视图跟这边）
        //第一个参数:对象  第二个参数:添加新的响应式属性  第三参数：新的属性的属性值
        this.$set(item, "flag", false);
      });
    },
    toEdit(row, index) {
      row.flag = true
      this.$nextTick(() => {
        //获取相应的input表单元素实现聚焦
        this.$refs[index].focus();
      });


    },
    deleteAttrValue(index) {

      this.attrInfo.attrValueList.splice(index, 1)
    },
    async addOrUpdateAttr() {
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(element => {
        if (element.valueName != '') {
          delete element.flag
          return true
        }
      });
      try {
        //发请求
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo);
        //展示平台属性的信号量进行切换
        this.isShowTable = true;
        //提示消失
        this.$message({ type: 'success', message: '保存成功' });
        //保存成功以后需要再次获取平台属性进行展示
        this.getAttrList();
      } catch (error) {
        this.$message('保存失败')
      }

    },
  }
}
</script>

<style scoped></style>